package com.cardbaobao.cardbabyclient.ui.activity;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.NoviceCreditCardAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.RecycleItemClickedCallback;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.NoviceCreditCardList;
import com.cardbaobao.cardbabyclient.model.result.BannerResult;
import com.cardbaobao.cardbabyclient.model.result.NoviceCreditCardListResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.cardbaobao.cardbabyclient.widget.divider.VerticalItemDecoration;
import com.cardbaobao.cardbabyclient.widget.refresh.FooterLoadMore;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.stx.xhb.xbanner.XBanner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 16:14.
 * 新手办卡
 */
public class NoviceCreditCardActivity extends BaseActivity {
    private static final int PAGE_START = 1;//分页开始页码
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.main_appbar)
    AppBarLayout appBarLayout;
    @BindView(R.id.xb_banner)
    XBanner xBanner;
    @BindView(R.id.srLayout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.footerLoadMore)
    FooterLoadMore footerLoadMore;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private NoviceCreditCardAdapter adapter;
    private List<NoviceCreditCardList.NoviceCreditCard> data;
    private NoviceCreditCardListResult listResult;
    private int pageNumber = PAGE_START;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        mCurrentPageId= Self.Page.app_newer_credit_card_page;

        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        initIntent();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ViewGroup.LayoutParams params = xBanner.getLayoutParams();
        int width = ScreenUtil.getScreenWidth(mContext);
        params.height = (int) (width * 28 / 75.0f);
        xBanner.setLayoutParams(params);
        xBanner.setmAutoPalyTime(Constant.BANNER_INTERVAL_TIME);

        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                srLayout.setEnableRefresh(verticalOffset==0);
            }
        });
        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNumber++;
                loadCards(pageNumber);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNumber = PAGE_START;
                loadCards(pageNumber);
            }
        });

        data = new ArrayList<>();
        adapter = new NoviceCreditCardAdapter(data);
        adapter.setRecycleItemClickedCallback(new RecycleItemClickedCallback() {
            @Override
            public void onRecycleItemClicked(int position) {
                SelfUtils.buriedClickData(Self.Action.app_click_novice_card_item,
                        Self.Action.app_click_novice_card_item_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                NoviceCreditCardList.NoviceCreditCard card = data.get(position);
                CommonJumpController controller = new CommonJumpController(mContext);
                if (card.getPage_type() == Constant.TYPE_NATIVE) {
                    controller.nativeDetailJump(Constant.PAGE_ZCC0101,
                            card.getDetail_id(),
                            card.getDetail_name(), null);
                } else {
                    Map<String,Object> extra=new HashMap<>();
                    extra.put(EventWebViewActivity.WEB_TYPE_I,18);
                    controller.h5WebJump(card.getPage_type(),card.getUrl(),card.getName(),extra);
                }
            }
        });
        final LinearLayoutManager layoutManager=
                new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE){
                    if(layoutManager.findFirstCompletelyVisibleItemPosition()==0){
                        appBarLayout.setExpanded(true,true);
                    }
                }
            }
        });
        VerticalItemDecoration decoration =
                new VerticalItemDecoration(0, DensityUtil.dp2px(mContext, 16.0f));
        recyclerView.addItemDecoration(decoration);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (xBanner.getParent() != null) {
            xBanner.startAutoPlay();
        }
        GoogleAnalyticsUtil.setScreenName(Google.CREDIT_NOVICE);
        UmengEventUtils.pageEvent(mContext,getString(R.string.event_0x04d));
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (xBanner.getParent() != null) {
            xBanner.stopAutoPlay();
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        loadBannerData();
        loadCards(pageNumber);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_novice_credit_card;
    }

    private void hideBanner() {
        //将xBanner从appBarLayout中移除，否则会导致滑动不流畅
        appBarLayout.removeView(xBanner);
        //设置tkRefreshLayout顶部margin
        ViewGroup.MarginLayoutParams marginLayoutParams =
                (ViewGroup.MarginLayoutParams) srLayout.getLayoutParams();
        marginLayoutParams.topMargin = DensityUtil.dp2px(16.0f);
        srLayout.setLayoutParams(marginLayoutParams);
    }

    private void loadBannerData() {
        Observable<String> observable= Api.getBannerData(Constant.GLB0317);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                hideBanner();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                BannerResult bannerResult = JsonUtil.json2Object(s, BannerResult.class);
                if (bannerResult.getCode() == Constant.SUC_CODE) {
                    if (bannerResult.getData() != null) {
                        final List<Banner.CarouselFigureListBean> data =
                                bannerResult.getData().getCarousel_figure_list();
                        if (data != null && data.size() > 0) {
                            xBanner.stopAutoPlay();
                            xBanner.setData(bannerResult.getData().getCarousel_figure_list(), null);
                            xBanner.setmAdapter(new XBanner.XBannerAdapter() {
                                @Override
                                public void loadBanner(XBanner banner, Object model, View view, int position) {
                                    ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL + ((Banner.CarouselFigureListBean) model).getImage(),
                                            (ImageView) view,
                                            R.mipmap.img_default_banner);
                                }
                            });
                            xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                                @Override
                                public void onItemClick(XBanner banner, int position) {
                                    SelfUtils.buriedClickData(Self.Action.app_click_novice_card_top_banner,
                                            Self.Action.app_click_novice_card_top_banner_des,
                                            mEnterPageTime,
                                            mCurrentPageId,
                                            mPrePageId);
                                    CommonJumpController controller = new CommonJumpController(mContext);
                                    Banner.CarouselFigureListBean bean = data.get(position);
                                    Map<String,Object> extra=new HashMap<>();
                                    extra.put(CommonJumpController.FROM_PAGE,"新手办卡-banner");
                                    extra.put(EventWebViewActivity.WEB_TYPE_I,17);
                                    controller.bannerJump(bean, extra);
                                }
                            });
                            xBanner.startAutoPlay();
                        } else {
                            hideBanner();
                        }
                    } else {
                        hideBanner();
                    }
                } else {
                    hideBanner();
                    ToastUtil.showToast(bannerResult.getMsg());
                }
            }
        });
    }

    private void loadCards(final int page) {
        Observable<String> observable=Api.getNoviceCards(String.valueOf(page));
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
                srLayout.finishRefresh();
                srLayout.finishLoadmore();
                if (page < listResult.getTotal_page()) {
                    //可加载更多数据
                    footerLoadMore.setStatePreLoading();
                    srLayout.setLoadmoreFinished(false);
                } else {
                    footerLoadMore.setStateNoMoreData();
                    srLayout.setLoadmoreFinished(true);
                }
            }

            @Override
            public void onError(Throwable e) {
                handlePageWhenFailure();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onNext(String s) {
                listResult = JsonUtil.json2Object(s, NoviceCreditCardListResult.class);
                if (listResult != null) {
                    if (listResult.getCode() == Constant.SUC_CODE) {
                        if (listResult.getData() != null) {
                            if (page == 1) {
                                //首页时，清除列表数据
                                data.clear();
                            }
                            data.addAll(listResult.getData().getTab_manager_six());
                            adapter.notifyDataSetChanged();
                        }
                    } else {
                        handlePageWhenFailure();
                        ToastUtil.showToast(listResult.getMsg());
                    }
                }
            }
        });
    }

    private void handlePageWhenFailure() {
        //加载出错时，处理分页
        pageNumber--;
        if (pageNumber < PAGE_START) {
            pageNumber = PAGE_START;
        }
    }
}
